from server import db, app_auth
from flask import jsonify, Blueprint, request, g
from server.model.booking import Booking
from server.model.field import Field
from server.model.order import Order, PayType, PurposeType, create_wechat_order
from server.model.gym import Gym
from server.model import set_field, query_by_field
from decimal import Decimal
from datetime import datetime, timedelta
import math

a_booking = Blueprint('app/booking', __name__)


@a_booking.route('', methods=['GET'])
@app_auth.login_required
def get_bookings():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in booking_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        booking_list = Booking.query.filter(Booking.user_id == g.user.id)

        if query_filter:
            booking_list = query_by_field(booking_list, query_filter, Booking)

        if start_time:
            booking_list = booking_list.filter(db.cast(Booking.create_time, db.Date) >= start_time)

        if end_time:
            booking_list = booking_list.filter(db.cast(Booking.create_time, db.Date) <= end_time)
        total = booking_list.count()

        booking_list = booking_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in booking_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get bookings error:", e)

    return jsonify({'code': 50001, 'message': "查询订场记录时发生错误"})


@a_booking.route('', methods=['POST'])
@app_auth.login_required
def add_bookings():
    """
    @@@
    #### Args:
            {
                gym_id: BIGINT(20    #球馆id
                field_id: BIGINT(20    #场地id
                user_id: BIGINT(20    #用户id
                from_time: DateTime    #开始时间
                to_time: DateTime    #结束时间
                price: DECIMAL(6    #价格
                status: TINYINT(unsigned=True)    #状态: 0:未使用 1:正在使用 2:已使用 3:已过期
                remind_on: Boolean    #开启提醒: 0:否 1:是
                remark: String(255)    #备注
            }
    #### Returns::
            {'code': 20000, 'message': "订场记录添加成功"}
            {'code': 50001, 'message': "添加订场记录时发生错误"}
    """

    args = request.get_json()
    bookings = args.get('bookings')
    gym_id = args.get('gym_id')
    body = args.get('body')
    # print('arg', args)

    try:
        gym = Gym.query.filter(Gym.id == gym_id).first()
        # 记录到订单时转换单位
        order = Order(user_id=g.user.id,
                      body=body,
                      pay_type=PayType.Online,
                      purpose=PurposeType.Booking,
                      validity_time=datetime.now() + timedelta(minutes=10))
        db.session.add(order)
        db.session.flush()

        amount = 0
        for book_args in bookings:
            book_date = book_args.get('book_date')
            field_id = book_args.get('field_id')
            field = Field.query.filter(Field.id == field_id).first()
            book_hour = book_args.get('book_hour')
            old_book = Booking.query.filter(Booking.field_id == field_id, Booking.book_date == book_date, Booking.book_hour == book_hour).first()
            if old_book:
                db.session.rollback()
                return jsonify({'code': 50001, 'message': "场地: %s %s:00:00-%s:00:00 时段 已经被预订,请重新选择" % (field.name, book_hour, book_hour + 1)})
            booking = Booking(gym_id=gym_id, user_id=g.user.id, user_phone=g.user.phone)
            set_field(booking, book_args)
            booking.order_id = order.id
            booking.price = price = gym.count_price(book_hour, book_date)
            amount += price
            db.session.add(booking)

        # 创建微信订单
        # order_no, wxpay_params = create_order(body, amount * 100, g.user.open_id)
        wxpay_params = ""
        order.total_fee = amount
        # order.order_no = order_no
        db.session.commit()

        return jsonify({'code': 20000, 'message': "订场记录添加成功", 'order': order.to_dict()})
    except Exception as e:
        db.session.rollback()
        print("add booking error:", e)

    return jsonify({'code': 50001, 'message': "添加订场记录时发生错误"})


@a_booking.route('/<int:pid>', methods=['GET'])
@app_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           booking/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in booking_list],
                            }
                """
    booking = Booking.query.filter_by(id=pid).first()
    if not booking:
        return jsonify({
            'code': 50002,
            'message': '查询订场记录不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': booking.to_dict(),
    })

# >>>>> auto generate end <<<<<
